<template>
	<view class="cart-page">
		<u-popup v-model="show" mode="bottom" :closeable="true" border-radius="24" height="600rpx">
			<view class="pop-tit">
				请选择配送方式
			</view>
			<view class="">
				<!-- 快递选项 -->
				<view class="option" @click="selectDelivery('express')">
					<view class="option-text">
						<text>快递</text>
						<text>￥{{freight[1].dictValue}}</text>
					</view>
					<view class="bot-chek" :class="{ selected: selectedDelivery === 'express' }">
						
						<image v-if="selectedDelivery === 'express'" :src="bg" mode=""></image>
						
					</view>
				</view>
				
				<!-- 到院领取选项 -->
				<view class="option" @click="selectDelivery('pickup')">
					<view class="option-text">
						<text>到院领取</text>
					</view>
					<view class="bot-chek" :class="{ selected: selectedDelivery === 'pickup' }">
						<image v-if="selectedDelivery === 'pickup'" :src="bg" mode=""></image>
						
					</view>
				</view>
			</view>
			<view class="btn-ok" @click="account">
				确认
			</view>
		</u-popup>



		<!-- <delVue :Visible="Visible" @isModal="isModal" @goStay="goStay" :oneText="oneText" :twoText="twoText"
			:threeText="threeText" :fourText="fourText" /> -->
		<view class="title">
			<view class="bg" :class="title != '' ? 'bg-color' : ''">
				
				<u-icon @click="goBack" size="36" name="arrow-left"></u-icon>
				<text>{{title}}</text>
				<view class="">
				</view>
			</view>
			
			
			<view class="title-two" v-if="token && cartData.length>0">
				<view class="">
					共{{cartData.length}}件商品
				</view>
				<view style="color: #CCA566;" class="" @click="toggleEditMode">
					{{ editButtonText  }}
				</view>
			</view>
		</view>
		<!-- 购物车商品列表 -->
		<view class="" v-if="token">
			<view class="" v-if="cartData.length>0">
				<scroll-view scroll-y="true" class="scroll-Y">
					<view class="cart-item" v-for="item in cartData" :key="item.id" @click="">
						<!-- 模拟复选框 -->

						<view :class="['checkbox', { selected: item.selected }]" class="checkbox"
							@click.top="toggleItemSelection(item)">
							<image v-if="item.selected" :src="togglebg" mode=""></image>
							<!-- <u-icon v-if="item.selected" color="#fff" size="32" name="checkmark"></u-icon> -->
						</view>



						<image :src="getFirstImage(item.goods.photoUrl)" class="item-image" />
						<view class="actions-main">
							<view class="item-details">
								<text>{{ item.goods.title }}</text>
							</view>
							<view class="main-item">
								<view class="box-text">
									￥
									<text>{{ item.goods.price }}</text>
								</view>

								<view class="item-actions">
									<view class="actions-btn" @click="adjustQuantity(item, -1)">-</view>
									<view class="actions-btn">{{ item.count }}</view>
									<view class="actions-btn" @click="adjustQuantity(item, 1)">+</view>
								</view>
							</view>
						</view>

					</view>
				</scroll-view>
			</view>
			<view class="" v-else>
				<view class="notlogin" @click="goShop">
					<view class="">
						购物车为空
					</view>
					<view class="">
						去购物
					</view>
				</view>
			</view>
			<!-- 结算区域 -->
			<view class="bot-tom">
				<view class="bot-btn">
					<view class="bot-chek">
						<view :class="['checkbox', { selected: isAllSelected }]" class="select-all"
							@click="toggleSelectAll">
							<image v-if="isAllSelected" :src="togglebg" mode=""></image>
							<!-- <u-icon v-if="isAllSelected" color="#fff" size="32" name="checkmark"></u-icon> -->
						</view>
						<text>全选</text>
					</view>
					<view v-if="!isEditMode" class="checkout">

						<view class="">
							<view class="yunfei">
								<text class="yun">含运费</text>
								<text class="total">合计:</text>
								<view class="box-text">
									￥
									<text>{{ totalPrice() }}</text>
								</view>
							</view>
							<view class="" style="font-size: 24rpx; color: #808080;">
								共优惠：￥0.00
							</view>
						</view>

						<!-- @click="checkout" -->
						<view class="delete-btn" @click="isModal">结算</view>
					</view>
					<!-- 删除选中商品按钮 -->
					<view v-else @click="removeSelectedItems" class="delete-btn">删除</view>
				</view>
			</view>
		</view>
		<view class="notlogin" v-else @click="login">
			<view class="">
				你还未登录
			</view>
			<view class="">
				去登录
			</view>
		</view>



	</view>
</template>

<script>
	import config from "../../utils/config";
	import {
		delgoodsCar,
		getregistration,
		goodsCar
	} from '../../service/api.js'
	import {
		toast,
		getStore,
		setStore
	} from "../../utils";
	import delVue from '../../components/del.vue'
	export default {
		components: {

			delVue
		},
		data() {
			return {
				togglebg: config.ossHost + '2025/01/03/b7e97ec044a3427180a2b3d13ffb10b2.png',
				bg: config.ossHost + '2025/01/03/b7e97ec044a3427180a2b3d13ffb10b2.png',
				selectedDelivery: 'express', // 当前选中的配送方式
				show:false,
				oneText: "确定",
				twoText: "暂时放弃",
				threeText: "是否要结算选中的商品",
				fourText: "提示",
				title: "购物车",
				Visible: false,
				// 模拟的购物车数据
				cartData: [],
				isAllSelected: false, // 是否全选
				isEditMode: false,
				token: "",
				delcartData: "",

				//创建订单传递参数
				setpaygoods: [{
					id: 0,
					memberId: "",
					addressId: "",
					count: ""
				}, ],
				freight: [],



			};
		},
		computed: {

			editButtonText() {
				return this.isEditMode ? '取消' : '编辑'; // 编辑模式时显示“取消”
			},
		},
		onLoad() {
			this.getcarriage();
			this.getgood();
		},
		onShow() {
			this.token = getStore("token") || null;
			this.info = JSON.parse(getStore("info")) || {};
			if (!this.token) {
				this.show = true
			}
			//赋值用户id
			this.setpaygoods[0].memberId = this.info.id;
		},
		methods: {
			
			goBack() {
				
				uni.navigateBack({
					delta: 1,
				});
				
				   // uni.switchTab({
				   //   url: '/pages/my/index'  // 跳转到首页
				   // });
				
				
			},
			
			
			selectDelivery(method) {
				
				// 选择配送方式
				this.selectedDelivery = method;
				
			},
			//购物车为空时
			goShop() {
				uni.navigateTo({
					url: '/outpatient/product/index'
				})
			},
			//获取运费价格
			async getcarriage() {
				let res = await getregistration("carriage");
				if (res.code == 200) {
					this.freight = res.rows;

				}
			},
			//请求购物车
			async getgood() {
				let res = await goodsCar()
				if (res.code == 200) {
					this.cartData = res.rows;
					this.cartData.forEach(item => {
						this.$set(item, 'selected', false); // 确保 selected 是响应式的
					});
					this.cartData[0].selected = true;
					this.toggleSelectAll();
				}
			},
			getFirstImage(photoUrl) {
				console.log(photoUrl,"这里是什么东西")
				if (photoUrl && typeof photoUrl === 'string' ) {
					
					return photoUrl.split(',')[0]; // 返回第一个图片的 URL
				} else {
					return photoUrl; // 替换为你的默认图片路径
				}
			},
			totalPrice() {
				return this.cartData.reduce((total, item) => {
					if (item.selected && item.goods && item.goods.price !== undefined) {
						return total + (item.goods.price * item.count);
					}
					return total;
				}, 0);
			},


			login() {
				uni.navigateTo({
					url: `/My/oneClicklogin/login`
				})
			},
			toggleEditMode() {
				this.isEditMode = !this.isEditMode;
			},
			adjustQuantity(item, delta) {

				// 增加或减少商品数量
				const targetItem = this.cartData.find(i => i.id === item.id);
				if (targetItem) {
					targetItem.count += delta;
					if (targetItem.count < 1) targetItem.count = 1; // 防止数量为负
				}
			},
			toggleItemSelection(item) {

				item.selected = !item.selected;

				this.totalPrice();
				this.updateSelectAllStatus();
			},
			toggleSelectAll() {
				// 切换全选状态
				this.isAllSelected = !this.isAllSelected;
				this.cartData.forEach(item => {
					item.selected = this.isAllSelected;
				});
			},
			async removeSelectedItems() {
				// 删除选中的商品
				let data = this.cartData;

				this.delcartData = data.filter(item => item.selected) // 筛选出选中的项
					.map(item => item.id) // 提取每个商品的 id
					.join(',');
				

				let res = await delgoodsCar(this.delcartData);
				if (res.code == 200) {
					toast("删除成功");
					this.getgood();
				}
			},
			account(){
				let data = this.cartData;
				const selectedItems = this.cartData.filter(item => item.selected);
				setStore("totalPrice", this.totalPrice());
				this.delcartData = data.filter(item => item.selected) // 筛选出选中的项
					.map(item => item.goods.id) // 提取每个商品的 id
					.join(',');
				setStore('selectedItems', JSON.stringify(selectedItems));
				this.show=false;
				// let res = await delgoodsCar(this.delcartData);
				uni.navigateTo({
					url: `/integration/carOrder/index?item=${JSON.stringify(selectedItems)}&totalPrice=${this.totalPrice()}&statusValue=100&selectedDelivery=${this.selectedDelivery}`
				})
			},
			isModal(item) {
				this.show=true;
				// this.Visible = item;
				

			},
			goStay(item) {
				this.Visible = item;
			},
			checkout() {
				this.Visible = true
				// 去结算


			},
			updateSelectAllStatus() {
				// 更新全选状态
				this.isAllSelected = this.cartData.every(item => item.selected);

			}
		}
	};
</script>

<style lang="scss" scoped>
	.title {
		background: #fff;
	}

	.scroll-Y {
		width: 702rpx;
		margin: auto;
		height: calc(100vh - 476rpx);

		padding-top: 24rpx;
	}

	.title-two {
		padding: 24rpx;
		display: flex;
		justify-content: space-between;

		color: #1A1A1A;
		padding-bottom: 24rpx;

		view {
			font-weight: bold;


		}
	}

	.actions-main {
		height: 180rpx;
		width: 400rpx;
		display: flex;
		flex-direction: column;

		.main-item {
			display: flex;
			justify-content: space-between;
		}
	}

	.actions-box {
		display: flex;
		justify-content: space-between;

		.item-actions {}

	}

	.actions-btn {
		line-height: 44rpx;
		text-align: center;
		width: 44rpx;
		height: 44rpx;
		background: #F2F2F2;
	}

	.actions-btn:nth-child(2) {
		margin: 0 4rpx;
	}

	.cart-page {}

	.cart-item {
		background: #FFFFFF;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
		display: flex;
		align-items: center;
		padding: 24rpx;
		margin-bottom: 24rpx;

	}

	.checkbox {
		width: 30rpx;
		height: 30rpx;
		border: 1rpx solid #ccc;
		border-radius: 50%;
		margin-right: 24rpx;
		display: flex;
		justify-content: center;
		align-items: center;

		cursor: pointer;
		background-color: white;
		image{
			width: 30rpx;
			height: 30rpx;
		}
	}

	.checkbox.selected {
		border: 1rpx solid #CCA566;
		background-color: #CCA566;
	}

	.item-image {
		width: 180rpx;
		height: 180rpx;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		margin-right: 16rpx;
	}

	.item-details {
		flex: 1;
	}

	.item-actions {
		display: flex;
		align-items: center;
	}

	button {
		margin: 5px;
	}

	.select-all {
		display: flex;
		align-items: center;

	}

	.delete-btn {
		width: 168rpx;
		height: 70rpx;
		background: #CCA566;
		border-radius: 4rpx 4rpx 4rpx 4rpx;
		text-align: center;
		line-height: 70rpx;
		margin-left: 16rpx;
		color: #FFFFFF;
	}

	.checkout {
		display: flex;
		align-items: center;
		// background-color: #f1f1f1;

	}

	.checkout button {
		width: 100%;
		padding: 10px;
		background-color: #ff6600;
		color: white;
		border: none;
	}

	.bot-btn {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.bot-chek {
			display: flex;
			align-items: center;
		}

		.yunfei {
			display: flex;
			font-size: 24rpx;
			color: #1A1A1A;
			align-items: baseline;

			.yun {
				color: #808080;
				margin-right: 10rpx;
			}

			.total {}

		}
	}

	.box-text {

		color: #FF7C54;

		text {
			font-weight: bold;
			font-size: 38rpx;
		}
	}

	.bot-tom {
		position: fixed;
		padding: 24rpx;
		background: #fff;
		left: 0;
		right: 0;
		bottom: 0;
		width: 702rpx;
		height: 120rpx;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
	}

	.notlogin {
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: calc(100vh - 370rpx);

		view {
			color: #B3B3B3;
		}

		view:last-child {
			width: 140rpx;
			margin-top: 20rpx;
			border-radius: 8rpx;
			padding: 12rpx 0;
			text-align: center;
			color: #fff;
			background: #CCA566;
		}
	}
	.pop-tit {
		text-align: center;
		padding: 32rpx 0;
		font-size: 32rpx;
		color: #1A1A1A;
		// border-bottom: 1rpx solid #E6E6E6;
	
	}
	.option {
		padding: 10rpx 24rpx;
		display: flex;
		justify-content: space-between;
	
		.bot-chek {
			border-radius: 50%;
			    width: 32rpx;
			    display: flex;
			    justify-content: center;
			    align-items: center;
			    height: 32rpx;
			    border: 1rpx solid #B3B3B3;
			    box-sizing: border-box;
	
			border: 1rpx solid #B3B3B3;
			image{
				width: 32rpx;
				height: 32rpx;
			}
		}
	
		.selected {
			// background: #CCA566;
			border: none;
	
		}
	}
	.btn-ok{
		width: 702rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		background: #CCA566;
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		margin: auto;
		margin-top: 250rpx;
	}
	
	
	.bg {
		width: 100%;
		height: 120rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 24rpx;
		padding-top: 65rpx;
	
	
		.title-img {
			width: 100rpx;
		}
	
		text {
			display: inline-block;
			color: #1a1a1a;
			font-size: 32rpx;
			font-weight: bold;
		}
	
		view {
			width: 100rpx;
		}
	}
	
	.bg-color {
		// background: #fff;
	}
</style>